package com.sctvcloud.zhaohua_sd.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.application.Cache;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.beans.MessageInfo;
import com.sctvcloud.zhaohua_sd.beans.MessageListVo;
import com.sctvcloud.zhaohua_sd.beans.SingleResult;
import com.sctvcloud.zhaohua_sd.beans.UserInfoBean;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.ui.adapter.MessageListAdapter;
import com.sctvcloud.zhaohua_sd.ui.utils.TitleUtils;
import com.sctvcloud.zhaohua_sd.utils.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyMessageCenterActivity extends BaseActivity implements MessageListAdapter.OnItemClickListener, CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {
    private static final int TO_MESSAGE_CENTER = 1;
    private static final int TO_LOGIN = 2;
    @BindView(R.id.message_list_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView messageListView;
    @BindView(R.id.title_top_edit)
    protected CustomFontTextView edit;
    @BindView(R.id.message_layout)
    protected LinearLayout messageLayout;
    @BindView(R.id.message_null)
    protected LinearLayout messageNull;
    @BindView(R.id.message_not_network)
    protected LinearLayout noNetwork;

    private MessageListAdapter adapter;
    private List<MessageInfo> msgList;
    private int currentIndex = 0;
    private int pageAll = 0;
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle("消息中心");
        edit.setText("设置");
        edit.setVisibility(View.VISIBLE);
        handler = new Handler( ){
            @Override
            public void handleMessage(Message msg) {
                if (null != msg) {
                    int what = msg.what;
                    switch (what) {
                        case TO_LOGIN:
                            toLoginView();
                            break;
                    }
                }
            }
        };
        initView();
    }


    @Override
    protected void initInject() {
        setContentView(R.layout.activity_message_center);
        ButterKnife.bind(this);
    }

    private void initView() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);

        LinearLayoutManager layoutmanager = new LinearLayoutManager(this);
        //设置RecyclerView 布局
        messageListView.setLayoutManager(layoutmanager);

        adapter = new MessageListAdapter(this, null);
        messageListView.setAdapter(adapter);
        adapter.setListener(this);
        refreshLayout.autoRefresh();
    }

    @Override
    public void onRefresh() {
        currentIndex = 1;
        getMessageData();
    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            if (pageAll > currentIndex) {
                currentIndex++;
                getMessageData();
            } else {
                refreshLayout.loadMoreComplete();
            }
        }
    }

    private void getMessageData() {
        if(-1==NetModeUtil.GetNetype(this)){
            //无网络
            messageLayout.setVisibility(View.GONE);
            messageNull.setVisibility(View.GONE);
            noNetwork.setVisibility(View.VISIBLE);
        }else if (UserManager.getInstance().getUser() != null) {
            ArrayMap<String, Object> p = new ArrayMap<>();
            p.put("pageIndex", currentIndex);
            p.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
            p.put("token", UserManager.getInstance().getUser().getToken());
            NetUtils.getNetAdapter().postGetMessageList(getOwnerName(), p, new AbsNetCallBack<MessageListVo>(MessageListVo.class) {
                @Override
                public void onSuc(MessageListVo messageListVo) {
                    pageAll = messageListVo.getPageAll();
                    currentIndex = messageListVo.getPageIndex();
                    JLog.e("", "messageList pageAll = " + pageAll + " ---index =" + currentIndex);
                    if (currentIndex == 1) {
                        msgList = messageListVo.getMsgList();
                    } else if (null != msgList) {
                        msgList.addAll(messageListVo.getMsgList());
                    }
                    if (msgList.size() > 0) {
                        messageLayout.setVisibility(View.VISIBLE);
                        messageNull.setVisibility(View.GONE);
                        noNetwork.setVisibility(View.GONE);
                        adapter.setData(msgList);
                        adapter.notifyDataSetChanged();
                    } else {
                        messageLayout.setVisibility(View.GONE);
                        messageNull.setVisibility(View.VISIBLE);
                        noNetwork.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onEnd() {
                    super.onEnd();
                    onNetFinish();

                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                }

                @Override
                public boolean whenLoginExpiredBackGround() {
                    Message msg = new Message();
                    msg.what = TO_LOGIN;
                    handler.sendMessage(msg);
                    return true;
                }
            });
        }else {
            toLogin();
        }
    }

    private synchronized void onNetFinish() {
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
        refreshLayout.setLoadMoreEnabled(currentIndex >= pageAll ? false : true);
    }

    @Override
    public void onItemClick(MessageInfo msgInfo) {
        //TODO 设置消息为已读
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "消息中心"));
        pairs.add(new Pair<>("行为类型", "点击"));
        GridsumWebDissector.getInstance().trackEvent(this, "", "消息详情", "", 200, pairs);
        Intent intent = new Intent(this, MessageInfoActivity.class);
        intent.putExtra(MessageInfoActivity.MESSAGE_CONTENT, msgInfo.getContent());
        intent.putExtra(MessageInfoActivity.MESSAGE_TIME, msgInfo.getDate());
        startActivity(intent);
        setMessageRead(msgInfo.getMsgId());
        setResult(RESULT_OK);
    }

    private void setMessageRead(String messageID) {
        for (int i = 0; i < msgList.size(); i++) {
            if (msgList.get(i).getMsgId().equalsIgnoreCase(messageID)) {
                //列表中设置为已读状态
                msgList.get(i).setStatus(1);
                break;
            }
        }
        adapter.setData(msgList);
        adapter.notifyDataSetChanged();
        ArrayMap<String, Object> p = new ArrayMap<>();
        p.put("msgId", messageID);
        p.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
        p.put("token", UserManager.getInstance().getUser().getToken());
        NetUtils.getNetAdapter().postSetReadMessage(getOwnerName(), p, new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult result) {
                if (result.isSuccess()) {
                    setResult(RESULT_OK);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });
    }

    @OnClick({R.id.title_top_edit})
    protected void click(View view) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "消息中心"));
        switch (view.getId()) {
            case R.id.title_top_edit:
                pairs.add(new Pair<>("行为类型", "点击"));
                GridsumWebDissector.getInstance().trackEvent(this, "", "消息设置", "", 200, pairs);
                Intent intent = new Intent(MyMessageCenterActivity.this, MessageSettingActivity.class);
                MyMessageCenterActivity.this.startActivityForResult(intent, TO_MESSAGE_CENTER);
                break;
        }
    }
    private void toLoginView() {
        Toast.makeText(MyMessageCenterActivity.this, "登录用户失效，请重新登录！", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, CODE_REQUEST_LOGIN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == CODE_REQUEST_LOGIN||requestCode == TO_MESSAGE_CENTER) && resultCode == RESULT_OK) {
            JLog.e("exchange city  ---", "");
            currentIndex = 1;
            getMessageData();
            setResult(RESULT_OK);
        }
    }
}
